<template>
  <div>
    <div class="box-border p-12px">
      <el-form ref="formRef" :rules="rules" :model="submitForm" label-width="100px" class="mt-12px">
        <div>
          <SubTitle title="策略基本信息" />
          <el-form-item label="策略名称：" required prop="strategyName">
            <ns-input v-model="submitForm.strategyName" clearable placeholder="请输入策略名称" />
          </el-form-item>
          <el-form-item label="策略描述：" prop="strategyDesc">
            <ns-input v-model="submitForm.strategyDesc" clearable placeholder="请输入策略描述" />
          </el-form-item>
        </div>
        <div class="mt-16px">
          <SubTitle title="策略基本信息">
            <el-button type="primary" class="ml-12px" @click="handleExpress">表达式生成</el-button>
          </SubTitle>
          <el-card shadow="never">
            <el-tabs v-model="tabName" class="demo-tabs">
              <el-tab-pane
                :label="tabNameList[tabKey]"
                :name="tabKey"
                v-for="(tab, tabKey) in strategyRule"
                :key="tabKey"
              >
                <el-card
                  class="mb-12px"
                  shadow="never"
                  v-for="(rules, index) in strategyRule[tabKey]"
                  :key="index"
                >
                  <div class="flex items-center">
                    规则{{ index + 1 }}
                    <div class="ml-auto mr-12px font-size-14px">
                      启用状态：
                      <el-switch v-model="rules.enable" />
                    </div>
                    <el-icon
                      class="cursor-pointer"
                      v-if="strategyRule[tabKey].length > 1"
                      @click="delRules(tabKey, index)"
                      ><Close
                    /></el-icon>
                  </div>
                  <el-table :data="rules.conditionDTOS" style="width: 100%">
                    <el-table-column label="序号" type="index" />
                    <el-table-column label="条件对象">
                      <template #default="scope">
                        <el-select v-model="scope.row.conditionObject">
                          <el-option
                            v-for="(ite, i) in conditionList"
                            :key="i"
                            :label="ite.label"
                            :value="ite.value"
                            v-show="ite.type == tabKey"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="条件类型">
                      <template #default="scope">
                        <el-select v-model="scope.row.codeType">
                          <el-option
                            v-for="(ite, i) in conditionTypeList"
                            :key="i"
                            :label="ite.label"
                            :value="ite.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="表达式">
                      <template #default="scope">
                        <ns-input
                          v-model="scope.row.regexContent.value"
                          v-if="scope.row.codeType !== 'SERVERLESS'"
                        />
                        <el-select v-model="scope.row.serverlessContentId" v-else>
                          <el-option
                            v-for="(algorithm, algorithmIndex) in algorithmList"
                            :key="algorithmIndex"
                            :label="algorithm.algorithmName"
                            :value="algorithm.id"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <!-- <el-table-column label="最少次数">
                      <template #default="scope">
                        <ns-input v-model.number="scope.row.keyWord" />
                      </template>
                    </el-table-column> -->
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button
                          :icon="Minus"
                          size="small"
                          circle
                          v-if="scope.$index !== 0"
                          class="ml-12px"
                          @click="delRow(tabKey, index, scope.$index)"
                        />
                        <el-button
                          :icon="Plus"
                          size="small"
                          circle
                          class="ml-12px"
                          v-if="rules.conditionDTOS.length === scope.$index + 1"
                          @click="addRow(tabKey, index, scope.$index)"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-form-item label="条件关系：">
                    <el-radio-group
                      v-model="rules.logicOperation"
                      @change="(v) => handleChange(v, rules)"
                    >
                      <el-radio label="or">全部为或</el-radio>
                      <el-radio label="and">全部为且</el-radio>
                      <!-- <el-radio label="not">全部为非</el-radio> -->
                    </el-radio-group>
                  </el-form-item>
                  <!-- <el-form-item m label="最少数量：" v-if="rules.logicOperation == 'or'">
                    <ns-input style="width: 230px" v-model="rules.minCount" />
                  </el-form-item> -->
                </el-card>
                <el-button @click="addRules(tabKey)">新增规则</el-button>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </el-form>
      <ExpressForm ref="expressRef" />
    </div>
    <div>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Plus, Minus, Close } from '@element-plus/icons-vue'
import { strategyCreate, strategyUpdate } from '@/api/strategyManage/strategy/index'
import { algorithmPage } from '@/api/strategyManage/algorithm/index'
import SubTitle from '@/components/SubTitle/index.vue'
import ExpressForm from './expressForm.vue'
import { t } from '@/hooks/web/useI18n'
import { cloneDeep } from 'lodash-es'

const message = useMessage() // 消息弹窗
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})

const tabName = ref('column')
const tabNameList = {
  column: '字段识别规则',
  table: '表识别规则',
  file: '文件识别规则'
}

const formRef = ref()
const submitForm = ref({
  strategyName: '',
  strategyDesc: ''
})
const rules = {
  strategyName: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }]
}

const conditionList = [
  {
    label: '字段名称',
    value: 'columnName',
    type: 'column'
  },
  {
    label: '字段描述',
    value: 'columnComment',
    type: 'column'
  },
  {
    label: '字段内容',
    value: 'columnContent',
    type: 'column'
  },
  {
    label: '表名称',
    value: 'tableName',
    type: 'table'
  },
  {
    label: '表描述',
    value: 'tableComment',
    type: 'table'
  },
  {
    label: '文件名称',
    value: 'fileName',
    type: 'file'
  },
  {
    label: '文件内容',
    value: 'fileContent',
    type: 'file'
  },
  {
    label: '文件扩展名',
    value: 'fileSuffix',
    type: 'file'
  }
]

const conditionTypeList = [
  {
    label: '正则',
    value: 'REGEX'
  },
  {
    label: '识别算法引用',
    value: 'SERVERLESS'
  },
  {
    label: '关键字',
    value: 'INCLUDE'
  }
]

const strategyRule = ref({
  column: [
    {
      id: guid(),
      enable: true,
      conditionDTOS: [
        {
          id: guid(),
          conditionObject: '',
          codeType: '',
          regexContent: {
            value: ''
          },
          serverlessContentId: ''
        }
      ],
      logicOperation: 'or'
    }
  ],
  table: [
    {
      id: guid(),
      enable: true,
      conditionDTOS: [
        {
          id: guid(),
          conditionObject: '',
          codeType: '',
          regexContent: {
            value: ''
          },
          serverlessContentId: ''
        }
      ],
      logicOperation: 'or'
    }
  ],
  file: [
    {
      id: guid(),
      enable: true,
      conditionDTOS: [
        {
          id: guid(),
          conditionObject: '',
          codeType: '',
          regexContent: {
            value: ''
          },
          serverlessContentId: ''
        }
      ],
      logicOperation: 'or'
    }
  ]
})

const expressRef = ref()
const handleExpress = () => {
  expressRef.value.open()
}

const addRules = (tabKey) => {
  strategyRule.value[tabKey].push({
    id: guid(),
    enable: true,
    conditionDTOS: [
      {
        id: guid(),
        conditionObject: '',
        codeType: '',
        regexContent: {
          value: ''
        },
        serverlessContentId: ''
      }
    ],
    logicOperation: 'or'
  })
}
const delRules = (tabKey, index) => {
  strategyRule.value[tabKey].splice(index, 1)
}

const handleChange = (v, rules) => {
  if (v == 'not') {
    rules.isNot = true
  } else {
    rules.isNot = false
  }
}

const addRow = (tabKey, index, rowIndex) => {
  strategyRule.value[tabKey][index].conditionDTOS.push({
    id: guid(),
    conditionObject: '',
    codeType: '',
    regexContent: {
      value: ''
    },
    serverlessContentId: ''
  })
}
const delRow = (tabKey, index, rowIndex) => {
  strategyRule.value[tabKey][index].conditionDTOS.splice(rowIndex, 1)
}

const confirm = async () => {
  const apiInterface = props.params.id ? strategyUpdate : strategyCreate
  formRef.value.validate(async (valid) => {
    if (valid) {
      const info = cloneDeep(strategyRule.value)
      for (let i in info) {
        info[i].forEach((item) => {
          item.logicOperation = item.isNot ? 'or' : item.logicOperation
        })
      }
      const data = await apiInterface({
        ...submitForm.value,
        type: 'amp',
        strategyRule: info
      })
      console.log('data', data)
      if (data) {
        message.success('操作成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

// 识别算法下拉列表
const algorithmList = ref([])
const getAlgorithm = async () => {
  const data = await algorithmPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  algorithmList.value = data.data
}

// 生成uuid
function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

onMounted(() => {
  getAlgorithm()
  if (props.params.id) {
    submitForm.value = props.params
    if (props.params.strategyRule) {
      strategyRule.value = JSON.parse(props.params.strategyRule)
      for (let i in strategyRule.value) {
        strategyRule.value[i].forEach((item) => {
          item.logicOperation = item.isNot ? 'not' : item.logicOperation
        })
      }
    }
  }
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
